package com.ccp.dev.system.configuration;

import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * springsecurity 访问拒绝自定义处理器。<br>
 * 接收AccessDeniedException 并交由accessDeniedUrl页面处理。<br>
 * 在处理页面中需要使用 AccessDeniedException ex=(AccessDeniedException)request.getAttribute("ex");
 * @author y
 */
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

	private String accessDeniedUrl;

	public String getAccessDeniedUrl() {
		return accessDeniedUrl;
	}
	
	public void setAccessDeniedUrl(String accessDeniedUrl) {
		this.accessDeniedUrl = accessDeniedUrl;
	}
	

	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException ex){
		request.setAttribute("javax.servlet.error.request_uri", request.getRequestURI());
		request.setAttribute("javax.servlet.error.exception", ex);
		request.setAttribute("javax.servlet.error.status_code", HttpStatus.FORBIDDEN.value());
		try{
			request.getRequestDispatcher(accessDeniedUrl).forward(request, response);
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}

}
